package action

import (
	"../global"
	"../model"
	"git.oschina.net/dxvgef/go-lib/validation"
	"github.com/go-pg/pg"
	"github.com/labstack/echo"
	"strconv"
	"strings"
	"time"
)

type User struct{}

//定义查询用的产品结构体
var Agents []struct {
	ID       int64
	TeamName string
}

//用户列表首页
func (*User) Index(ctx echo.Context) (err error) {
	response := make(map[string]interface{})
	response["error"] = ""

	var query model.User
	if ctx.QueryParam("agent_id") != "" {
		agent_id, err := strconv.ParseInt(ctx.QueryParam("agent_id"), 10, 64)
		if err != nil {
			global.Logger.Error("agent_id数据类型转换出错：" + err.Error())
			response["error"] = "系统错误"
			return ctx.JSON(500, response)
		}
		query.AgentID = agent_id
	}
	if ctx.QueryParam("nickname") != "" {
		query.NickName = ctx.QueryParam("nickname")
	}
	if ctx.QueryParam("fullname") != "" {
		query.FullName = ctx.QueryParam("fullname")
	}
	if ctx.QueryParam("mobile") != "" {
		query.Mobile = ctx.QueryParam("mobile")
	}
	if ctx.QueryParam("reg_time1") != "" {
		t, err := time.ParseInLocation("2006-01-02T15:04", ctx.QueryParam("reg_time1"), global.TimeLocal)
		if err != nil {
			global.Logger.Error("reg_time1数据类型转换是失败：" + err.Error())
			query.SearchTime1 = 0
		}
		query.SearchTime1 = t.Unix()
	}
	if ctx.QueryParam("reg_time2") != "" {
		t, err := time.ParseInLocation("2006-01-02T15:04", ctx.QueryParam("reg_time2"), global.TimeLocal)
		if err != nil {
			global.Logger.Error("reg_time1数据类型转换是失败：" + err.Error())
			query.SearchTime2 = 0
		}
		query.SearchTime2 = t.Unix()
	}

	var UserModel model.UserModel
	res, err := UserModel.GetUser(&query, []string{}, &model.ListParams{})
	if err != nil {
		if err == pg.ErrNoRows {
			global.Logger.Error("用户不存在：" + err.Error())
			response["error"] = "系统错误"
			return ctx.JSON(500, response)
		} else {
			global.Logger.Error("查询用户出错：" + err.Error())
			response["error"] = "系统错误"
			return ctx.JSON(500, response)
		}
	}

	if len(res) == 0 {
		response["data"] = ""
	} else {
		response["data"] = res
	}

	//查询出代理，用于筛选
	_, err = global.DB.Query(&Agents, `SELECT "id", "team_name" FROM agent`)
	if err != nil {
		global.Logger.Error("查询代理商错误：" + err.Error())
		response["error"] = "系统错误"
		return ctx.JSON(500, response)
	}
	response["agents"] = Agents

	return ctx.JSON(200, response)
}

//显示单个用户的各项信息
func (*User) Show(ctx echo.Context) (err error) {
	response := make(map[string]interface{})
	response["error"] = ""

	if ctx.Param("user_id") == "" {
		response["error"] = "缺少参数user_id"
		return ctx.JSON(200, response)
	}

	user_id, err := strconv.ParseInt(ctx.Param("user_id"), 10, 64)
	if err != nil {
		global.Logger.Error("user_id数据类型转换失败：" + err.Error())
		response["error"] = "系统错误"
		return ctx.JSON(500, response)
	}

	var UserModel model.UserModel
	res, err := UserModel.GetUser(&model.User{ID: user_id}, []string{}, &model.ListParams{Limit: 1})
	if err != nil {
		if err == pg.ErrNoRows {
			global.Logger.Error("用户不存在：" + err.Error())
			response["error"] = "系统错误"
			return ctx.JSON(500, response)
		} else {
			global.Logger.Error("查询用户出错：" + err.Error())
			response["error"] = "系统错误"
			return ctx.JSON(500, response)
		}
	}

	if len(res) == 0 || res[0].ID == 0 {
		response["error"] = "用户不存在"
		return ctx.JSON(200, response)
	}

	//定义筛选时间
	var SearchTime1, SearchTime2 int64
	if ctx.QueryParam("search_time1") != "" {
		if t, err := time.ParseInLocation("2006-01-02T15:04", ctx.QueryParam("search_time1"), global.TimeLocal); err == nil {
			SearchTime1 = t.Unix()
		}
	}
	if ctx.QueryParam("search_time2") != "" {
		if t, err := time.ParseInLocation("2006-01-02T15:04", ctx.QueryParam("search_time2"), global.TimeLocal); err == nil {
			SearchTime2 = t.Unix()
		}
	}
	if SearchTime1 != 0 && SearchTime2 != 0 && SearchTime1 > SearchTime2 {
		response["error"] = "开始时间不能大于结束时间"
		return ctx.JSON(200, response)
	}

	//统计该用户的订单，充值，提现总数和总额
	data_count := make(map[string]interface{})
	var Count int64
	if SearchTime1 != 0 && SearchTime2 != 0 {
		//用户订单总数，总额
		if _, err = global.DB.Query(&Count,
			`SELECT count(*) FROM "order_trade_completed" WHERE user_id = ? AND buy_time >= ? AND sell_time <= ?`,
			res[0].ID, SearchTime1, SearchTime2); err == nil {
			data_count["order_count"] = Count
		}

		if _, err = global.DB.Query(&Count, `SELECT sum("amount") FROM "order_trade_completed" WHERE user_id = ? AND buy_time >= ? AND sell_time <= ?`,
			res[0].ID, SearchTime1, SearchTime2); err == nil {
			data_count["order_amount"] = Count
		}

		//用户盈利订单总数，总额
		if _, err = global.DB.Query(&Count, `SELECT count(*) FROM "order_trade_completed" WHERE user_id = ? AND income_amount > ? AND buy_time >= ? AND sell_time <= ?`,
			res[0].ID, 0, SearchTime1, SearchTime2); err == nil {
			data_count["income_count"] = Count
		}
		if _, err = global.DB.Query(&Count, `SELECT sum("income_amount") FROM "order_trade_completed" WHERE user_id = ? AND income_amount > ? AND buy_time >= ? AND sell_time <= ?`,
			res[0].ID, 0, SearchTime1, SearchTime2); err == nil {
			data_count["income_amount"] = Count
		}

		//用户亏损订单总数，总额
		if _, err = global.DB.Query(&Count, `SELECT count(*) FROM "order_trade_completed" WHERE user_id = ? AND income_amount < ? AND buy_time >= ? AND sell_time <= ?`,
			res[0].ID, 0, SearchTime1, SearchTime2); err == nil {
			data_count["outcome_count"] = Count
		}
		if _, err = global.DB.Query(&Count, `SELECT sum("amount") FROM "order_trade_completed" WHERE user_id = ? AND income_amount < ? AND buy_time >= ? AND sell_time <= ?`,
			res[0].ID, 0, SearchTime1, SearchTime2); err == nil {
			data_count["outcome_amount"] = Count
		}

		//充值订单总数，总额
		if _, err = global.DB.Query(&Count, `SELECT count(*) FROM "recharge_order" WHERE user_id = ? AND status = ? AND start_time >= ? AND end_time <= ?`,
			res[0].ID, true, SearchTime1, SearchTime2); err == nil {
			data_count["recharge_count"] = Count
		}
		if _, err = global.DB.Query(&Count, `SELECT sum("amount") FROM "recharge_order" WHERE user_id = ? AND status = ? AND start_time >= ? AND end_time <= ?`,
			res[0].ID, true, SearchTime1, SearchTime2); err == nil {
			data_count["recharge_amount"] = Count
		}

		//提现订单总数，总额
		if _, err = global.DB.Query(&Count, `SELECT count(*) FROM "withdraw_order" WHERE user_id = ? AND status = ? AND start_time >= ? AND end_time <= ?`,
			res[0].ID, true, SearchTime1, SearchTime2); err == nil {
			data_count["withdraw_count"] = Count
		}
		if _, err = global.DB.Query(&Count, `SELECT sum("amount") FROM "withdraw_order" WHERE user_id = ? AND status = ? AND start_time >= ? AND end_time <= ?`,
			res[0].ID, true, SearchTime1, SearchTime2); err == nil {
			data_count["withdraw_amount"] = Count
		}
	} else {

		if _, err = global.DB.Query(&Count, `SELECT count(*) FROM "order_trade_completed" WHERE user_id = ?`, res[0].ID); err == nil {
			data_count["order_count"] = Count
		}
		if _, err = global.DB.Query(&Count, `SELECT sum("amount") FROM "order_trade_completed" WHERE user_id = ?`, res[0].ID); err == nil {
			data_count["order_amount"] = Count
		}

		//用户盈利订单总数，总额
		if _, err = global.DB.Query(&Count, `SELECT count(*) FROM "order_trade_completed" WHERE user_id = ? AND income_amount > ?`, res[0].ID, 0); err == nil {
			data_count["income_count"] = Count
		}
		if _, err = global.DB.Query(&Count, `SELECT sum("income_amount") FROM "order_trade_completed" WHERE user_id = ? AND income_amount > ?`, res[0].ID, 0); err == nil {
			data_count["income_amount"] = Count
		}

		//用户亏损订单总数，总额
		if _, err = global.DB.Query(&Count, `SELECT count(*) FROM "order_trade_completed" WHERE user_id = ? AND income_amount < ?`, res[0].ID, 0); err == nil {
			data_count["outcome_count"] = Count
		}
		if _, err = global.DB.Query(&Count, `SELECT sum("amount") FROM "order_trade_completed" WHERE user_id = ? AND income_amount < ?`, res[0].ID, 0); err == nil {
			data_count["outcome_amount"] = Count
		}

		//充值订单总数，总额
		if _, err = global.DB.Query(&Count, `SELECT count(*) FROM "recharge_order" WHERE user_id = ? AND status = ?`, res[0].ID, true); err == nil {
			data_count["recharge_count"] = Count
		}
		if _, err = global.DB.Query(&Count, `SELECT sum("amount") FROM "recharge_order" WHERE user_id = ? AND status = ?`, res[0].ID, true); err == nil {
			data_count["recharge_amount"] = Count
		}

		//提现订单总数，总额
		if _, err = global.DB.Query(&Count, `SELECT count(*) FROM "withdraw_order" WHERE user_id = ? AND status = ?`, res[0].ID, true); err == nil {
			data_count["withdraw_count"] = Count
		}
		if _, err = global.DB.Query(&Count, `SELECT sum("amount") FROM "withdraw_order" WHERE user_id = ? AND status = ?`, res[0].ID, true); err == nil {
			data_count["withdraw_amount"] = Count
		}
	}

	//查询用户的充值订单
	if GetData(res[0].ID, "RechargeOrderModel", SearchTime1, SearchTime2) == false {
		response["error"] = "系统错误"
		return ctx.JSON(500, response)
	}
	response["recharge_orders"] = GetData(res[0].ID, "RechargeOrderModel", SearchTime1, SearchTime2)

	//查询用户的提现订单
	if GetData(res[0].ID, "WithdrawOrderModel", SearchTime1, SearchTime2) == false {
		response["error"] = "系统错误"
		return ctx.JSON(500, response)
	}
	response["withdraw_orders"] = GetData(res[0].ID, "WithdrawOrderModel", SearchTime1, SearchTime2)

	//查询用户历史购买记录
	if GetData(res[0].ID, "OrderTradeCompletedModel", SearchTime1, SearchTime2) == false {
		response["error"] = "系统错误"
		return ctx.JSON(500, response)
	}
	response["history_orders"] = GetData(res[0].ID, "OrderTradeCompletedModel", SearchTime1, SearchTime2)

	//查询用户的持仓订单
	if GetData(res[0].ID, "OrderTradeInCompleteModel", SearchTime1, SearchTime2) == false {
		response["error"] = "系统错误"
		return ctx.JSON(500, response)
	}
	response["now_orders"] = GetData(res[0].ID, "OrderTradeInCompleteModel", SearchTime1, SearchTime2)

	//查询用户的下级用户
	if GetData(res[0].ID, "UserModel", SearchTime1, SearchTime2) == false {
		response["error"] = "系统错误"
		return ctx.JSON(500, response)
	}
	response["his_users"] = GetData(res[0].ID, "UserModel", SearchTime1, SearchTime2)

	response["data"] = res[0]
	response["data_count"] = data_count
	return ctx.JSON(200, response)
}

//修改用户资料
func (*User) Edit(ctx echo.Context) (err error) {
	response := make(map[string]interface{})
	response["error"] = ""

	if ctx.Param("user_id") == "" {
		response["error"] = "缺少参数user_id"
		return ctx.JSON(200, response)
	}

	user_id, err := strconv.ParseInt(ctx.Param("user_id"), 10, 64)
	if err != nil {
		global.Logger.Error("user_id数据类型转换失败：" + err.Error())
		response["error"] = "系统错误"
		return ctx.JSON(500, response)
	}

	var UserModel model.UserModel
	result, err := UserModel.GetUser(&model.User{ID: user_id}, []string{"id"}, &model.ListParams{Limit: 1})
	if err != nil {
		if err == pg.ErrNoRows {
			global.Logger.Error("用户不存在：" + err.Error())
			response["error"] = "用户不存在"
			return ctx.JSON(200, response)
		} else {
			global.Logger.Error("查询用户出错：" + err.Error())
			response["error"] = "系统错误"
			return ctx.JSON(500, response)
		}
	}
	if len(result) == 0 || result[0].ID == 0 {
		response["error"] = "用户不存在"
		return ctx.JSON(200, response)
	}

	var query model.User
	query.ID = result[0].ID
	//校验客户端传来的数据是否合法
	if ctx.FormValue("email") != "" {
		if validation.Mail(ctx.FormValue("email")) == false {
			response["error"] = "电邮地址不正确"
			return ctx.JSON(200, response)
		}
		query.Email = ctx.FormValue("email")
	}
	if ctx.FormValue("mobile") != "" {
		if validation.Mobile(ctx.FormValue("mobile")) == false {
			response["error"] = "手机号码格式不正确"
			return ctx.JSON(200, response)
		}
		query.Mobile = ctx.FormValue("mobile")

	}
	if ctx.FormValue("fullname") != "" {
		if validation.FullName(ctx.FormValue("fullname")) == false {
			response["error"] = "姓名不正确"
			return ctx.JSON(200, response)
		}
		query.FullName = ctx.FormValue("fullname")

	}

	if ctx.FormValue("bank_number") != "" {
		Len := len(ctx.FormValue("bank_number"))
		if Len != 16 && Len != 19 {
			response["error"] = "银行卡号不正确"
			return ctx.JSON(200, response)
		}
		query.BankNumber = ctx.FormValue("bank_number")

	}
	if ctx.FormValue("nickname") != "" {
		query.NickName = ctx.FormValue("nickname")
	}

	if ctx.FormValue("idcard_number") != "" {
		if len(ctx.FormValue("idcard_number")) != 18 {
			response["error"] = "身份证号码不正确"
			return ctx.JSON(200, response)
		}
		query.IDCardNumber = ctx.FormValue("idcard_number")
	}

	if ctx.FormValue("balance") != "" {
		balance, err := strconv.ParseFloat(ctx.FormValue("balance"), 64)
		if err != nil {
			global.Logger.Error("balance数据类型转换出错：" + err.Error())
			response["error"] = "系统错误"
			return ctx.JSON(500, response)
		}
		if balance < 0 {
			response["error"] = "用户余额必须大于0"
			return ctx.JSON(500, response)
		}
		query.Balance = int64(balance * 100) //单位变为分,再转成int64，并进行赋值
	}
	if ctx.FormValue("deleted") != "" {
		if ctx.FormValue("deleted") == "true" {
			query.Deleted = true
		} else {
			query.Deleted = false
		}
	}

	err = UserModel.EditUser(&query)
	if err != nil {
		global.Logger.Error("修改用户资料出错：" + err.Error())
		response["error"] = "系统错误"
		return ctx.JSON(500, response)
	}

	return ctx.JSON(200, response)
}

//删除用户
func (*User) Delete(ctx echo.Context) (err error) {
	response := make(map[string]interface{})
	response["error"] = ""

	if ctx.Param("user_ids") == "" {
		response["error"] = "缺少参数user_ids"
		return ctx.JSON(200, response)
	}

	var deleteIDs []int64
	var stringIDs []string

	ids := ctx.Param("user_ids")
	stringIDs = strings.Split(ids, ",")
	for _, v := range stringIDs {
		id, err := strconv.ParseInt(v, 10, 64)
		if err != nil {
			global.Logger.Error("user_id数据类型转换出错")
			response["error"] = "系统错误"
			return ctx.JSON(500, response)
		}
		deleteIDs = append(deleteIDs, id)
	}
	//判断所传的用户ID是否在表中都存在
	var user_ids []model.User
	err = global.DB.Model(&user_ids).Column("id").WhereIn("id IN (?)", pg.In(deleteIDs)).Select()
	if err != nil {
		global.Logger.Error("查找用户ID出错：" + err.Error())
		response["error"] = "系统错误"
		return ctx.JSON(500, err.Error())
	}
	if len(user_ids) != len(deleteIDs) {
		response["error"] = "参数中含有不存在的用户ID"
		return ctx.JSON(200, response)
	}
	//判断所传的用户是否存在未完成的持仓订单
	var user_orders []model.OrderTradeInComplete
	for _, v := range deleteIDs {
		err = global.DB.Model(&user_orders).Where("user_id=?", v).Select()
		if err != nil {
			global.Logger.Error("查找用户的未完成订单出错：" + err.Error())
			response["error"] = "系统错误"
			return ctx.JSON(500, err.Error())
		}
		if len(user_orders) != 0 {
			response["error"] = "用户尚有未完成的订单，无法直接删除"
			return ctx.JSON(500, response)
		}
	}

	//开启事物，删除用户和用户相关记录
	tx, err := global.DB.Begin()
	if err != nil {
		global.Logger.Error("事物开启失败：" + err.Error())
		response["error"] = "系统错误"
		return ctx.JSON(500, err.Error())
	}

	//删除用户的充值、提现、购买记录
	if _, err = tx.Model(&model.RechargeOrder{}).WhereIn("user_id in (?)", pg.In(deleteIDs)).Delete(); err != nil {
		tx.Rollback()
		global.Logger.Error("删除用户的充值订单记录出错：" + err.Error())
		response["error"] = "系统错误"
		return ctx.JSON(500, err.Error())
	}
	if _, err = tx.Model(&model.WithdrawOrder{}).WhereIn("user_id in (?)", pg.In(deleteIDs)).Delete(); err != nil {
		tx.Rollback()
		global.Logger.Error("删除用户的提现订单记录出错：" + err.Error())
		response["error"] = "系统错误"
		return ctx.JSON(500, err.Error())
	}
	if _, err = tx.Model(&model.OrderTradeCompleted{}).WhereIn("user_id in (?)", pg.In(deleteIDs)).Delete(); err != nil {
		tx.Rollback()
		global.Logger.Error("删除用户的历史订单记录出错：" + err.Error())
		response["error"] = "系统错误"
		return ctx.JSON(500, err.Error())
	}
	//查找出要删除的下级用户，并把他们的parent_id改成自己的ID
	var his_users []model.User
	if err = global.DB.Model(&his_users).WhereIn("parent_id in (?)", pg.In(deleteIDs)).Select(); err != nil {
		global.Logger.Error("查询用户的下级用户出错：" + err.Error())
		response["error"] = "系统错误"
		return ctx.JSON(500, err.Error())
	}

	for _, v := range his_users {
		if _, err = tx.Model(&model.User{}).Where("id=?", v.ID).Set("parent_id=?", v.ID).Update(); err != nil {
			tx.Rollback()
			global.Logger.Error("修改用户的下级用户出错：" + err.Error())
			response["error"] = "系统错误"
			return ctx.JSON(500, err.Error())
		}
	}
	if len(deleteIDs) > 1 {
		if _, err = tx.Model(&model.User{}).WhereIn("id in (?)", pg.In(deleteIDs)).Delete(); err != nil {
			tx.Rollback()
			global.Logger.Error("删除用户出错：" + err.Error())
			response["error"] = "系统错误"
			return ctx.JSON(500, err.Error())
		}
	} else {
		if _, err = tx.Model(&model.User{}).WhereIn("id=?", deleteIDs[0]).Delete(); err != nil {
			tx.Rollback()
			global.Logger.Error("删除用户出错：" + err.Error())
			response["error"] = "系统错误"
			return ctx.JSON(500, err.Error())
		}

	}
	err = tx.Commit()
	if err != nil {
		global.Logger.Error("事物提交出错：" + err.Error())
		response["error"] = "系统错误"
		return ctx.JSON(500, err.Error())
	}
	return ctx.JSON(200, response)
}
